/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.materials;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.service.materials.MaterialService;
import com.qinyeit.serviceapp.utils.LocalUtils;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.date.DateUtils;
import com.qinyetech.springstage.core.entity.search.SearchFilterHelper;
import com.qinyetech.springstage.core.entity.search.SearchOperator;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.BeanConvertUtil;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;

import com.qinyeit.serviceapp.entity.MaterialCategory;
import com.qinyeit.serviceapp.service.materials.MaterialCategoryService;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * ClassName: MaterialCategorysController <br/>
 * Function: materialCategory [物品类别] <br/>
 * date: 2018-11-07 11:40:01 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/materials/materialCategorys")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_materialCategory:read",name ="物品类别",deleteAble = false)
public class MaterialCategorysController extends BaseManagementController{

	@Autowired
	private MaterialCategoryService materialCategoryService;
	@Autowired
	private MaterialService materialService;
    //TODO include的字段,支持jsonPath
	private final String [] keys = {"id","no","name","parentId","parentName","dishesCategoryId"};

    @RequiresPermissions("management_materialCategory:show")
    @PermissionInfo(code = "management_materialCategory:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable,Long storeId){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        //菜品库下的 或者 共享的
        searchable.addSearchFilter(SearchFilterHelper.or(
                SearchFilterHelper.newCondition("storeId", SearchOperator.eq,storeId),
                SearchFilterHelper.newCondition("storeId",SearchOperator.isNull,null)
        ));
        Page<MaterialCategory> materialCategoryPage = materialCategoryService.findAll(searchable);
        List<MaterialCategory> materialCategories= materialCategoryPage.getContent();
        for(int i=0;i<materialCategories.size();i++){
            for(int j=0;j<materialCategories.size();j++){
                if(materialCategories.get(i).getParentId()==null){
                    materialCategories.get(i).setParentName("");
                    break;
                }
                if(materialCategories.get(i).getParentId()==materialCategories.get(j).getId()){
                    materialCategories.get(i).setParentName(materialCategories.get(j).getName());
                    break;
                }

            }
        }
        return ok("查询成功", JSONUtils.include(materialCategoryPage, keys));
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(Long storeId){
        QyMap map=QyMap.NEW();
        MaterialCategory category = new MaterialCategory();
        category.setParentId(0L);
        category.setNo(materialCategoryService.getNextNo("01",CurrentAccountUtils.getAuthenticatedMerchantGroupID()));
        map.setv("materialCategory",JSONUtils.include(category, keys));
        initFormDate(map,storeId);
        return ok("初始化成功", map);
    }

    @RequiresPermissions("management_materialCategory:create")
    @PermissionInfo(code = "management_materialCategory:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@ModelAttribute @Valid MaterialCategory materialCategory, BindingResult bindingResult){
//        if(materialCategoryService.exists(buildExists(null, "no", materialCategory.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if(materialCategoryService.exists(SearchableUtils.buildExists(materialCategory.getId(), "no", materialCategory.getNo()))){
            return fail("编号已经存在");
        }
        if(materialCategoryService.exists(SearchableUtils.buildExists(materialCategory.getId(), "name", materialCategory.getName()))){
            return fail("名称已经存在");
        }
        if(StringUtils.isBlank(materialCategory.getNo())){
            return fail("请输入编号后保存");
        }
        if(StringUtils.isBlank(materialCategory.getName())){
            return fail("请输入名称后保存");
        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }

        materialCategory.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        materialCategory.setUuid(LocalUtils.getUUID());
        materialCategory.setUpdateTimestamp(DateUtils.current());
        materialCategoryService.save(materialCategory);
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute MaterialCategory materialCategory){
        return ok("查询成功", JSONUtils.include(materialCategory, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute MaterialCategory materialCategory,Long storeId){
        QyMap map=QyMap.NEW();
        map.setv("materialCategory",JSONUtils.include(materialCategory, keys));
        initFormDate(map,storeId); //TODO 如果没有需要初始化的数据，测则删除该行
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_materialCategory:update")
    @PermissionInfo(code = "management_materialCategory:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid MaterialCategory materialCategory,BindingResult bindingResult){
        if(materialCategoryService.exists(SearchableUtils.buildExists(materialCategory.getId(), "no", materialCategory.getNo()))){
            return fail("编号已经存在");
        }
        if(materialCategoryService.exists(SearchableUtils.buildExists(materialCategory.getId(), "name", materialCategory.getName()))){
            return fail("名称已经存在");
        }
        if(StringUtils.isBlank(materialCategory.getNo())){
            return fail("请输入编号后保存");
        }
        if(StringUtils.isBlank(materialCategory.getName())){
            return fail("请输入名称后保存");
        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        materialCategory.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        materialCategory.setUpdateTimestamp(DateUtils.current());
        materialCategoryService.update(materialCategory);
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_materialCategory:destory")
    @PermissionInfo(code = "management_materialCategory:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        //判断当前类别下是否存在原料 如果存在将不能删除
        MaterialCategory category = materialCategoryService.findById(id);
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchFilter(SearchFilterHelper.or(
                SearchFilterHelper.newCondition("category.parentIds_like", category.getParentIds()+category.getId()+"/"),
                SearchFilterHelper.newCondition("category.id_eq", category.getId())
        ));
        Long count = materialService.count(searchable);
        if(count>0){
            return fail("该类别已使用，不允许删除");
        }
        category.setUpdateTimestamp(DateUtils.current());
        materialCategoryService.update(category);
        materialCategoryService.logicDelete(id);
        return ok("删除成功", null);
    }

    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            MaterialCategory materialCategory = materialCategoryService.findById(Long.valueOf(id));
            model.addAttribute(materialCategory);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap,Long storeId){
        List<MaterialCategory> list=materialCategoryService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),storeId,true);
        MaterialCategory materialCategory=new MaterialCategory();
        materialCategory.setId(0l);
        materialCategory.setName("所有类别");
        materialCategory.setNo("0");
        list.add(0,materialCategory);
        qyMap.setv("treeData", BeanConvertUtil.listToDataTable(list,keys));
    }

}